package com.yao.presenter

import com.alibaba.fastjson.JSON
import com.base.mvp.BasePresenter
import com.yao.AppConfig
import com.yao.http.Http
import com.yao.http.Result
import com.yao.presenter.bean.IndexDataBean
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import java.util.*

class SearchPresenter : BasePresenter<SearchContract.View, SearchContract.Model>(), SearchContract.Presenter {
    override fun getModel(): SearchContract.Model {
        return SearchModel()
    }

    override fun getSearchData(str: String) {
        if (isViewAttached) {
            mView.showLoading()
            val flowable = mModel.getSearchData(str)
            try {
                mDisposable = flowable.subscribe({
                    mView.hideLoading()
                    if (it.code == 1) {
                        mView.onSuccessData(it.data)
                    } else {
                        mView.onFail(it.code, it.msg)
                    }
                }, {
                    mView.hideLoading()
                    it.message?.let { it1 -> mView.onFail(0, it1) }
                })
            } catch (e: Exception) {
                mView.hideLoading()
                mView.onError(e)
            }
        }
    }

    class SearchModel : SearchContract.Model {
        override fun getSearchData(str: String): Flowable<Result<List<IndexDataBean.ChildrenBean>>> {
            val paramsMap = HashMap<String, String>()
            paramsMap["searchVal"] = str
            val body =
                RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JSON.toJSONString(paramsMap))
            return http.getSearchData(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
        }

        override fun destroy() {
            Http.cancleAll(AppConfig.Http.API_SEARCH)
        }

        override fun getHttp(): SearchContract.Api {
            return Http.getInstance().retrofit.create(SearchContract.Api::class.java)
        }
    }
}